import React, {  useCallback, useContext, useEffect, useState } from 'react'
import { Layout, Spin, message } from 'antd';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';

import { Context } from '@/App';
import { reqUser } from '@/api/api';
import './home.less'

import HomeHeader from '@/components/HomeUI/Header/HomeHeader';
import HomeSider from '@/components/HomeUI/Sider/HomeSider';
import HomeContent from '@/components/HomeUI/Content/HomeContent';

const { Footer } = Layout

export default function Home() {
  const [urlKey, setUrlKey] = useState()

  const context = useContext(Context);
  const navigate = useNavigate();
  const location = useLocation();

  // 欢迎语
  const { pathname } = useLocation();
  const welcome = pathname === '/home' || pathname === '/home/';

  const getRole = useCallback((values) => {
    console.log("数据获取角色信息");
    reqUser(values).then(
      res => {
        if (res.status === 200) {
          context.setRole(res.data[0])
        } else if (res.status === 201) {
          message.error('找不到用户')
          navigate('/login', { replace: true })
        }
      },
      rej => {
        navigate('/login', { replace: true })
      }
    )
  }, [context, navigate])


  const redirection = useCallback(() => {
    let values = JSON.parse(window.sessionStorage.getItem("role"))
    // 重定向到登录
    if (!values) {
      navigate('/login', { replace: true })
      return
    }
    // 数据库拿权限
    getRole(values)
  }, [navigate, getRole])

  // 重定向login
  useEffect(() => {
    redirection()
    const currentUrl = location.pathname;
    setUrlKey(currentUrl.replace('/home/', ''));
  }, [])

  // 导航
  const changUrl = (url, replace, selectKey) => {
    navigate(url, replace)
    console.log(selectKey);
    setUrlKey(selectKey)
  }

  // 退出
  const goOut = () => {
    window.sessionStorage.removeItem("role")
    navigate('/login', { replace: true })
    context.setRole(null)
  }

  return (
    <>
      <Layout style={{ height: "100vh" }} className="home">
        <HomeHeader
          changUrl={changUrl}
          goOut={goOut}
          role={context?.role}
        />
        {
          !context.role ? <Spin size='large' className='loading' /> :
            <Layout>
              <HomeSider changUrl={changUrl} urlKey={urlKey} />
              <Layout style={{ height: "100%" }}>
                <div className='content-box'>
                    {welcome && <HomeContent />}
                    <Outlet></Outlet>
                </div>
                <Footer className='home-footer'>West City educational Administration System By Tian Huiwen</Footer>
              </Layout>
            </Layout>
        }
      </Layout>
    </>
  );
}